<template>
  <el-dialog
    class="custom-dialog"
    v-model="visibleModal"
    width="1240"
    append-to-body
    align-center
    :close-on-click-modal="false"
    :show-close="false"
    center
    @close="handleClose"
  >
    <template #header>
      <div class="custom-header">
        <span>业务流程 </span>
        <img src="@/assets/images/close.png" alt="Close" @click="handleClose" class="close-button" />
      </div>
    </template>
    <div class="content">
      <div ref="nodeGraph" id="nodeContainer"></div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, toRefs, nextTick, onMounted, onUnmounted } from 'vue'
import { Graph } from '@antv/x6'
import '@antv/x6-vue-shape'
import CustomSonNode from './customSonNode.vue'
// import { customJson } from './data.js'
import { customJson } from './mock.js'
import { autoLayout } from './common'
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  actionType: {
    type: String,
    default: 'add',
  },
})
const { dialogVisible } = toRefs(props)
const emit = defineEmits(['update:dialogVisible', 'submitSuccess'])
let visibleModal = ref(false) // 弹窗显示与隐藏
visibleModal.value = dialogVisible.value

const registCustom = () => {
  Graph.registerEdge(
    'bpmn-edge',
    {
      inherit: 'edge',
      attrs: {
        line: {
          stroke: '#81d2f7',
          strokeWidth: 4,
        },
      },
    },
    true,
  )
  // 方式2：注册 vue component
  Graph.registerNode(
    'custom-node',
    {
      inherit: 'vue-shape',
      width: 200,
      height: 180,
      component: {
        template: `<CustomSonNode />`,
        components: {
          CustomSonNode,
        },
      },
    },
    true,
  )
}

const nodeGraph = ref(null)
// 获取数据并渲染
const fetchAndRender = async () => {
  if (!nodeGraph.value || typeof nodeGraph.value.fromJSON !== 'function') {
    // 还没初始化好，直接返回
    return
  }

  try {
    // 本地开发用 mock 数据
    const data = customJson
    // 实际联调用 axios
    // const res = await axios.get(`/api/flow?projectType=${selectedType.value}`)
    // const data = res.data

    const { nodes, edges } = data
    const layoutedNodes = autoLayout(nodes, edges)

    const x6Data = {
      nodes: layoutedNodes.map((n) => ({
        ...n,
        shape: 'custom-node',
        data: n.data || {},
      })),
      edges: edges.map((e) => ({
        ...e,
        shape: 'bpmn-edge',
        router: { name: 'manhattan' },
      })),
    }
    nodeGraph.value.fromJSON(x6Data)
    nodeGraph.value.centerContent() //让图表内容在弹窗中居中显示
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}
const init = () => {
  registCustom()
  nodeGraph.value = new Graph({
    container: document.getElementById('nodeContainer'),
    width: 1200,
    height: 600,
    connecting: {
      router: 'orth',
    },
    // grid: true,
    interacting: false, // 不允许拖拽
    scroller: {
      enabled: true,
      pannable: true, //
      padding: 0, // 设置 padding 为 0
      pageVisible: false, // 关闭页面可见性相关布局
      autoResize: true,
    },
    mousewheel: {
      enabled: true,
      zoomAtMousePosition: true,
      modifiers: 'ctrl',
      minScale: 0.2,
      maxScale: 2,
    },
    panning: {
      enabled: true,
      eventTypes: ['leftMouseDown', 'rightMouseDown', 'middleMouseDown'],
    },
  })
  fetchAndRender()
}

// 关闭弹窗
const handleClose = () => {
  visibleModal.value = false
  emit('update:dialogVisible', false)
}

onMounted(() => {
  nextTick(() => {
    init()
  })
})
onUnmounted(() => {
  if (nodeGraph.value) {
    nodeGraph.value.dispose()
    nodeGraph.value = null
  }
})
</script>
<style scoped lang="scss"></style>
